from flask import Flask, render_template, request, redirect, url_for, flash
from pymongo import MongoClient
import spider_movie_money
from spider_movie_top import *
import pandas as pd
# from spider_movie_top2 import MovieSpider

# Flask应用配置
app = Flask(__name__)

# 数据库连接
client = MongoClient('mongodb://localhost:27017/')
user_info_db = client['user_info_db']
users = user_info_db['users']

# 指定模板文件夹路径
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
STATIC_DIR = os.path.join(BASE_DIR, '../static')
TEMPLATE_DIR = os.path.join(BASE_DIR, '../templates')

app = Flask(__name__, static_folder=STATIC_DIR,
            template_folder=TEMPLATE_DIR)

app.secret_key = 'a_very_secret_key_123456'

@app.route('/', methods=['GET', 'POST'])
def first():
    """点击后第一界面"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        # 查询用户信息
        user = users.find_one({'username': username, 'password': password})
        if user:
            flash('登录成功', 'success')
            return render_template("index.html")
        else:
            flash('用户名或密码错误', 'error')

    return render_template("Login.html")


@app.route('/login', methods=['GET', 'POST'])
def login():
    """处理用户登录请求"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        # 查询用户信息
        user = users.find_one({'username': username, 'password': password})
        if user:
            flash('登录成功', 'success')
            return render_template("index.html")
        else:
            flash('用户名或密码错误', 'error')

    return render_template("Login.html")


@app.route('/register', methods=['GET', 'POST'])
def register():
    """处理用户注册请求"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        # 检查用户是否已存在
        if users.find_one({'username': username}):
            flash('用户名已存在，请选择其他用户名', 'error')
            return render_template('Register.html')

        # 插入新用户信息
        users.insert_one({'username': username, 'password': password})
        flash('注册成功', 'success')
        return redirect(url_for('login'))

    return render_template("Register.html")


@app.route('/index')
def index():
    """主页路由"""
    return render_template("index.html")


@app.route('/index2')
def start_spider_route():
    """启动爬虫并返回主页"""
    return render_template("index.html")


# 读取 CSV 文件中的数据
def read_csv_data(csv_path):
    data = []
    try:
        with open(csv_path, 'r', encoding='utf-8-sig') as csv_file:
            reader = csv.DictReader(csv_file)
            for row in reader:
                data.append(row)
    except Exception as e:
        print(f"读取 CSV 文件时出错: {e}")
    return data


@app.route('/score')
def score():
    base_dir = os.path.abspath(os.path.dirname(__file__))
    csv_file = os.path.join(base_dir, '../豆瓣新片榜.csv')
    # 读取数据
    movie_data = read_csv_data(csv_file)
    movie_names = []
    ratings = []
    for row in movie_data:
        movie_names.append(row['影片中文名'])
        rating = row['评分']
        if rating:
            ratings.append(float(rating))
        else:
            ratings.append(0)

    return render_template('score.html', score=movie_names, number=ratings)


@app.route('/word')
def word():
    """词云页面"""
    return render_template("word.html")


@app.route('/movie')
def movie():
    """热门电影页面"""
    try:
        # 读取 CSV 文件
        base_dir = os.path.abspath(os.path.dirname(__file__))
        csv_file = os.path.join(base_dir, '../北美票房榜.csv')
        data = pd.read_csv(csv_file)

        # 提取电影名称和票房数据
        movie_names = data['电影名称'].tolist()
        box_office = data['电影票房'].tolist()

        # 生成 series.data 格式的数据
        series_data = [{"name": name, "value": value}
                       for name, value in zip(movie_names, box_office)]
        print(series_data)

        month = spider_movie_money.main()
        print(month)

    except Exception as e:
        print(f"数据处理错误: {e}")
        # 可以添加错误处理逻辑
        series_data = []
        movie_names = []
        month = []

    return render_template('hotMovie.html',
                           month=month, series_data=series_data, movie_name=movie_names)


@app.route('/word_search', methods=['POST'])
def word_search():
    """关键词搜索功能"""
    keyword = request.form.get('keyword')
    print(f"接收到的关键词: {keyword}")
    results = []

    try:
        base_dir = os.path.abspath(os.path.dirname(__file__))
        db_path = os.path.join(base_dir, '../word_frequency.db')
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        query = "SELECT word, count FROM word_frequency WHERE word LIKE ?"
        cursor.execute(query, ('%' + keyword + '%',))
        results = cursor.fetchall()
        conn.close()
        # print(f"查询结果数量: {len(results)}")

    except Exception as e:
        print(f"查询出错: {e}")

    if results:
        word = results[0][0]
        count = results[0][1]
    else:
        word = "未找到相关词"
        count = 0

    return render_template("word2.html", count=count, word=word)


@app.route('/movie_search', methods=['POST'])
def movie_summary_search():
    keyword = request.form.get('keyword')
    results = []
    try:
        base_dir = os.path.abspath(os.path.dirname(__file__))
        db_path = os.path.join(base_dir, '../影片Top.db')
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        query = "SELECT introduction FROM movie WHERE cname LIKE ?"
        cursor.execute(query, ('%' + keyword + '%',))
        results = cursor.fetchall()
        conn.close()
    except Exception as e:
        print(f"查询出错: {e}")
    if results:
        summary = results[0][0]
    else:
        summary = "未找到相关电影概述"
    return render_template("movie_info.html", summary=summary, keyword=keyword)


if __name__ == '__main__':
    app.run(debug=True)